<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Settings extends Controller_Initial_Page {
    
    public function action_index()
    {
       $this->action_desktop();
    }
    
    public function action_desktop()
    {
       $content_view = View::factory('content');      
       $settings_template_view = View::factory('settings/template'); 
          
       $settings_template_view->set('content', $this->generate_desktop());
       $settings_template_view->set('menu_selected', 1);
       $content_view->set('content', $settings_template_view);
       
       $this->template->set('body', $content_view);   
    }
    
    public function action_ajax_desktop()
    {
        $content = array('content' => $this->generate_desktop()->render());
        $this->response->body(json_encode($content));     
    }
    
    private function generate_desktop()
    {
        $settings_desktop_view = View::factory('settings/desktop');
        
        $user_model = Auth::instance()->get_user();
        $desktop_model = $user_model->desktop;
        
        $settings_desktop_view->set('wallpaper_path', $desktop_model->wallpaper->path(true,'mini', false));
        $settings_desktop_view->set('color', $desktop_model->color);
        $settings_desktop_view->set('grid', $desktop_model->grid);
        return $settings_desktop_view;
    }
    
    public function action_profile($section = null)
    {
       $content_view = View::factory('content');      
       $settings_template_view = View::factory('settings/template'); 
       
       $settings_template_view->set('content',  $this->generate_all_profile($section)->render());
       $settings_template_view->set('menu_selected', 2);
       $content_view->set('content', $settings_template_view);
       $this->template->set('body', $content_view);
    }
    
   
    public function action_ajax_profile($section = null)
    {
           switch ($section)
           {
               case 'experience':
                   $content = array('content' => $this->generate_experience()->render());
                   break;
               
               case 'education':
                   $content = array('content' => $this->generate_education()->render());
                   break;
               
               case 'additional':
                   $content = array('content' => $this->generate_additional()->render());
                   break;
               
               case 'profile':
                   $content = array('content' => $this->generate_profile()->render());
                   break; 
               
               default :
                   $content = array('content' => $this->generate_all_profile()->render());
                   break; 
           }
                      
           $this->response->body(json_encode($content));   
    }
    
    private function generate_profile()
    {
         $user_model = Auth::instance()->get_user();
         $user_profile_model = $user_model->user_profile; 
         $user_field_model = $user_model->fields;        
         $field_model = ORM::factory('field');
         $country_model = ORM::factory('country');
        
         $settings_profile_profile_view = View::factory('settings/profile/profile');
         $settings_profile_profile_view->set('profile', $user_profile_model);
         $settings_profile_profile_view->set('my_fields', $user_field_model->find_all()
                                                                           ->as_array('id'));
         
         $settings_profile_profile_view->set('countries', $country_model->get_all());
         $settings_profile_profile_view->set('fields', $field_model->get_all());                  
         return $settings_profile_profile_view;
    }
       
    private function generate_experience()
    {
         $user_model = Auth::instance()->get_user();
         $user_experience_model = $user_model->user_experiences; 
        
         $settings_profile_experience_view = View::factory('settings/profile/experience');
         $settings_profile_experience_view->set('experiences', $user_experience_model->find_all());
         return $settings_profile_experience_view;
    }
    
    private function generate_education()
    {
         $user_model = Auth::instance()->get_user();
         $user_education_model = $user_model->user_educations; 
         
         $settings_profile_education_view = View::factory('settings/profile/education');
         $settings_profile_education_view->set('educations', $user_education_model->find_all());
         return $settings_profile_education_view;
    }
    
    private function generate_additional()
    {
         $user_model = Auth::instance()->get_user();
         $user_additional_model = $user_model->user_additional; 
        
         $settings_profile_additional_view = View::factory('settings/profile/additional');
         $settings_profile_additional_view->set('additional', $user_additional_model);
         return $settings_profile_additional_view;
    }
    
    private function generate_all_profile($section = null)
    {
        switch ($section)
        {
            case 'experience':
                $content = $this->generate_experience();
                $selected = 2; 
                break;

            case 'education':
                $content = $this->generate_education();
                $selected = 3;
                break;
               
            case 'additional':
                $content = $this->generate_additional();
                $selected = 4;
                break;
                                              
            default :
                $content = $this->generate_profile();
                $selected = 1;
                break;  
           }
           
           $settings_profile_view = View::factory('settings/profile');
           $settings_profile_view->set('content',$content);
           $settings_profile_view->set('menu_selected', $selected);
           return $settings_profile_view;
    }
    
    
    public function action_ajax_save_profile()
    {
        if ($_POST)
        {
             $user_model = Auth::instance()->get_user();
             $user_profile_model = $user_model->user_profile; 
             
             $_POST['user_id'] = $user_model->id;
             $_POST['url'] = URL::title($_POST['name'].' '.$_POST['surname'],'-',true);
             $_POST['country_iso'] = $_POST['country']; 
             
             $user_profile_model->values($_POST, array('name',
                                                       'surname',
                                                       'url',
                                                       'description',
                                                       'address',
                                                       'birth_date',
                                                       'country_iso',
                                                       'user_id'));  
             
             $external_values = array('field' => (array_key_exists('field',$_POST) AND !empty($_POST['field'])));
             $extra_rules = Validation::factory($external_values)
                            ->rule('field', 'not_empty')
                            ->labels(array('field' => __('Field')));
             try
             {                
                 $user_profile_model->save($extra_rules);
                 
                 $user_model->remove('fields');
                 $user_model->add('fields',$_POST['field']);
                 
                 $output = array('success'=>'true',
                                 'message'=>'Profile data saved');
             }
             catch (ORM_Validation_Exception $e)
             {
                 $output = array('success' => 'false', 
                                 'message' => 'Oh no!', 
                                 'errors'  => $e->errors('validation'));
             }
                           
             $this->response->body(json_encode($output));
             
        }
    }
    
    public function action_ajax_save_desktop()
    {
        
        if ($_POST)
        {
             $user_model = Auth::instance()->get_user();
             $desktop_model = $user_model->desktop; 
                          
             $_POST['user_id'] = $user_model->id;   
                
             $desktop_model->values($_POST, array('color',
                                                  'grid',                                                   
                                                  'user_id'));  
             
             try
             {                
                 $desktop_model->save();

                 $output = array('success'=>true,
                                 'message'=>'Desktop settings saved');
             }
             catch (ORM_Validation_Exception $e)
             {
                 $output = array('success' => false, 
                                 'message' => 'Oh no!', 
                                 'errors'  => $e->errors('validation'));
             }
                           
             $this->response->body(json_encode($output));
             
        }
    }
    
    public function action_ajax_save_experience()
    {
        if ($_POST)
        {
            $user_model = Auth::instance()->get_user();
            $user_experience_model = $user_model->user_experiences; 
           
            $date = new DateTime();
            $date->setDate($_POST['start_date_year'], $_POST['start_date_month'], 1);
            
            $_POST['date_start'] = $date->format('Y-m-d H:i:s');
            
            if (array_key_exists('working', $_POST) AND $_POST['working'] == '1')
            {
                $_POST['date_end'] =  null;
            }
            else
            {
                 $date->setDate($_POST['end_date_year'], $_POST['end_date_month'], 1);
                 $_POST['date_end'] = $date->format('Y-m-d H:i:s');
            }
                       
            //if expericence_id exists edit row, else add new row
            if (array_key_exists('experience_id', $_POST))
            {
                $user_experience_model->where('id','=',$_POST['experience_id'])->find();
                $user_experience_model->values($_POST, array('employer',
                                                             'position',
                                                             'responsibilities',
                                                             'date_start',
                                                             'date_end'));
               
                
                $action = 'edit';
                $form_open = true;
            }
            else
            {
                $_POST['user_id'] = $user_model->id;                
                $user_experience_model->values($_POST, array('employer',
                                                             'position',
                                                             'responsibilities',
                                                             'date_start',
                                                             'date_end',
                                                             'user_id'));
                
                $action = 'add';
                $form_open = false;
            }
            
            try
            {          
                 $user_experience_model->save();
                 
                 $content = View::factory('settings/profile/experience_row', array('experience' => $user_experience_model,
                                                                                   'form_open'  => $form_open))
                            ->render();
                 
                 $output = array('success' => 'true',
                                 'message' => $action == 'edit' ? 'Experience has been edited' : 'Experience has been added',
                                 'action'  => $action,
                                 'content' => $content);
                 
                 //add notification
                 $notification_data = array(':employer'   => $_POST['employer'],
                                            ':position'   => $_POST['position'],
                                            ':date_start' => $_POST['date_start'],
                                            ':date_end'   => $_POST['date_end']);
                 
                 $notification_model = ORM::factory('notification');
                 $notification_model->user_id = $user_model->id;
                 $notification_model->event_type = 'EXPERIENCE_CHANGED';
                 $notification_model->event_params = serialize($notification_data);
                 $notification_model->save();
            }
            catch(ORM_Validation_Exception $e)
            {
                 $output = array('success' => 'false',
                                 'message' => 'Oh no',
                                 'errors'  => $e->errors('validation'));
            }
           
            // echo View::factory('profiler/stats');
             $this->response->body(json_encode($output));
        }
    }
    
    public function action_ajax_save_education()
    {
        if ($_POST)
        {
            $user_model = Auth::instance()->get_user();
            $user_education_model = $user_model->user_educations; 
           
            $date = new DateTime();
            $date->setDate($_POST['start_date_year'],$_POST['start_date_month'], 1);
            
            $_POST['date_start'] = $date->format('Y-m-d H:i:s');
            
            if (array_key_exists('studying', $_POST) AND $_POST['studying'] == '1')
            {
                $_POST['date_end'] = null;
            }
            else
            {
                 $date->setDate($_POST['end_date_year'], $_POST['end_date_month'], 1);
                 $_POST['date_end'] = $date->format('Y-m-d H:i:s');
            }
                       
            //if education_id exists edit row, else add new row
            if (array_key_exists('education_id', $_POST))
            {
                $user_education_model->where('id','=',$_POST['education_id'])->find();
                $user_education_model->values($_POST, array('degree',
                                                             'school',
                                                             'faculty',
                                                             'date_start',
                                                             'date_end'));
                $action = 'edit';
                $form_open = true;
            }
            else
            {
                $_POST['user_id'] = $user_model->id;                
                $user_education_model->values($_POST, array('degree',
                                                             'school',
                                                             'faculty',
                                                             'date_start',
                                                             'date_end',
                                                             'user_id'));
                $action = 'add';
                $form_open = false;
            }
            
            
            
            try
            {
                 $user_education_model->save();
                 
                 $content = View::factory('settings/profile/education_row', array('education' => $user_education_model,
                                                                                  'form_open'  => $form_open))
                            ->render();
                 
                 $output = array('success' => 'true',
                                 'message' => $action == 'edit' ? 'Education has been edited' : 'Education has been added',
                                 'action'  => $action,
                                 'content' => $content);
                 
                 //add notification
                 $notification_data = array(':school'     => $_POST['school'],
                                            ':faculty'    => $_POST['faculty'],
                                            ':date_start' => $_POST['date_start'],
                                            ':date_end'   => $_POST['date_end']);
                 
                 $notification_model = ORM::factory('notification');
                 $notification_model->user_id = $user_model->id;
                 $notification_model->event_type = 'EDUCATION_CHANGED';
                 $notification_model->event_params = serialize($notification_data);
                 $notification_model->save();
            }
            catch (ORM_Validation_Exception $e)
            {
                 $output = array('success' => 'false',
                                 'message' => 'Oh no no no!',
                                 'errors'  => $e->errors('validation'));
            }
           
            $this->response->body(json_encode($output));
        }
       
    }
    
    public function action_ajax_save_additional()
    {
        if ($_POST)
        {
             $user_model = Auth::instance()->get_user();
             $user_additional_model = $user_model->user_additional; 
             
             $_POST['user_id'] = $user_model->id;
             
             $user_additional_model->values($_POST, array('achievements',
                                                          'courses',
                                                          'organizations',
                                                          'languages',
                                                          'interests',
                                                          'user_id'));             
             $user_additional_model->save();
                         
             $output = array('success'=>'true',
                             'message'=>'Additional data saved'); 
             
             $this->response->body(json_encode($output));            
        }
    }
    
    public function action_ajax_delete_experience($experience_id)
    {
        $user_model = Auth::instance()->get_user();
        $user_experience_model = $user_model->user_experiences; 
        $user_experience_model->where('id','=',(int)$experience_id)
                              ->find()
                              ->delete();       
    }
    
    public function action_ajax_delete_education($education_id)
    {
        $user_model = Auth::instance()->get_user();
        $user_experience_model = $user_model->user_educations; 
        $user_experience_model->where('id','=',(int)$education_id)
                              ->find()
                              ->delete();       
        
    }
    
    public function action_account($section = null)
    {
       $content_view = View::factory('content');      
       $settings_template_view = View::factory('settings/template'); 
       
       $settings_template_view->set('content',  $this->generate_all_account($section)->render());
       $settings_template_view->set('menu_selected', 4);
       $content_view->set('content', $settings_template_view);
       $this->template->set('body', $content_view);
    }
    
    public function action_ajax_account($section = null)
    {

           switch ($section)
           {
               case 'change_data':
                   $content = array('content' => $this->generate_change_data()->render());
                   break;
               
             /*  case 'delete_account':
                   $content = array('content' => $this->generate_delete_account()->render());
                   break;  */
               
               default :
                   $content = array('content' => $this->generate_all_account()->render());
                   break; 
           }
                      
           $this->response->body(json_encode($content));
    }
    
    
    
    private function generate_all_account($section = null)
    {
        switch ($section)
        {

     /*       case 'delete_account':
                $content = $this->generate_delete_account();
                break;        */      
                                              
            default :
                $content = $this->generate_change_data();
                break;  
           }
           
           $settings_account_view = View::factory('settings/account');
           $settings_account_view->set('content',$content); 
           return $settings_account_view;    
    }
    
    public function action_ajax_save_change_data()
    {
        if ($_POST)
        {
            $user_model = Auth::instance()->get_user();
            
            try
            {
                $user_model->update_user($_POST, array('username',
                                                       'password',
                                                       'email'));
                $output = array('success' => 'true',
                                'message' => 'Account settings saved');
             }
             catch (ORM_Validation_Exception $e)
             {
                 $output = array('success' => 'false', 
                                 'message' => 'Oh no!', 
                                 'errors'  => $e->errors('validation'));
             }
                           
             $this->response->body(json_encode($output));

        }
        
    }
    
    private function generate_change_data()
    {
         $user_model = Auth::instance()->get_user();
         $settings_account_view = View::factory('settings/account/change_data');
         $settings_account_view->set('account',$user_model);
         return $settings_account_view;
    }
    
    public function action_ajax_upload_wallpaper()
    {
        $file = Uploader::factory();
        $errors = $file->validate('2M', array('jpg','jpeg','png'));
        
        if(!$errors)
        {
            
            $user_model = Auth::instance()->get_user();
            $user_desktop_model = $user_model->desktop;
            $file_model = $user_desktop_model->wallpaper;
         
            $file_model->name      = 'wallpaper_'.time();
            $file_model->extension = $file->extension;
            $file_model->size      = $file->size;
            $file_model->folder    = 'user_wallpaper';
           
            $file_model->save(); 
            
            $user_desktop_model->file_id = $file_model->id;
            $user_desktop_model->save();
            
            $target_directory = UPLPATH.'/user_wallpaper/';
            $new_file_name = $file_model->id;
            $ext = $file_model->extension;

            // if directory doesn't exist - create 
            if(!is_dir($target_directory))
                mkdir($target_directory,0755);
            
            $image = Image::factory($file->tmp_name);
            $image->resize(1600, 900, Image::INVERSE);
            $image->crop(1600, 900);
            $image->save($target_directory.$new_file_name.'.'.$ext);

            $image->resize(278, 176,Image::INVERSE);
            $image->crop(278, 176);
            $image->save($target_directory.$new_file_name.'_mini.'.$ext);
            
            $output = array('success' => true,
                            'message' => $file_model->path(false,'mini',true));
            
        }
        else
        {
             $output = $errors;
        } 
        
            echo htmlspecialchars(json_encode($output), ENT_NOQUOTES); 
    }
    
    public function action_upload_wallpaper()
    {
        $this->auto_render = false;
        $this->action_ajax_upload_wallpaper();
    }
    
    public function action_ajax_upload_user_photo()
    {
         $file = Uploader::factory();
         $errors = $file->validate('2M', array('jpg','jpeg','png') );    
       
        if (!$errors)
        {
            $user_model = Auth::instance()->get_user();
            $user_profile_model = $user_model->user_profile;
            $file_model = $user_profile_model->photo;
         
            $file_model->name      = 'photo_'.time();
            $file_model->extension = $file->extension;
            $file_model->size      = $file->size;
            $file_model->folder    = 'user_photo';
           
            $file_model->save(); 
            
            $user_profile_model->file_id = $file_model->id;
            $user_profile_model->save();
            
            $target_directory = UPLPATH.'/user_photo/';
            $new_file_name = $file_model->id;
            $ext = $file_model->extension;

            // if directory doesn't exist - create 
            if(!is_dir($target_directory))
                mkdir($target_directory,0755);

            $image = Image::factory($file->tmp_name);
            $image->resize(400, 400);
            $image->save($target_directory.$new_file_name.'.'.$ext);

            $image->resize(105, 105,Image::INVERSE);
            $image->crop(105, 105);
            $image->save($target_directory.$new_file_name.'_square.'.$ext);

            $image->resize(47,47);
            $image->save($target_directory.$new_file_name.'_mini_square.'.$ext); 
            
            $output = array('success' => true,
                            'message' => $file_model->path(true,'square',false));
            
        }
        else
        {
            $output = $errors;
        }
        
        echo htmlspecialchars(json_encode($output), ENT_NOQUOTES);
      
 			
    }
    
    public function action_upload_user_photo()
    {
        $this->auto_render = false;
        $this->action_ajax_upload_user_photo();
    }
    
    public function action_ajax_delete_wallpaper()
    {
        $user_model = Auth::instance()->get_user();
        $user_desktop_model = $user_model->desktop;
        $file_model = $user_desktop_model->wallpaper;
        
        if( $file_model->loaded())
        {
            //delete file;
            unlink($file_model->real_path('mini'));
            unlink($file_model->real_path());

            $file_model->delete();
            $user_desktop_model->file_id = null;
            $user_desktop_model->save();
        }
                
    }
    
    public function action_ajax_delete_photo()
    {
        $user_model = Auth::instance()->get_user();
        $user_profile_model = $user_model->user_profile;
        $file_model = $user_profile_model->photo;
        
        if( $file_model->loaded())
        {
            //delete file;
            unlink($file_model->real_path('mini_square'));
            unlink($file_model->real_path('square'));
            unlink($file_model->real_path());

            $file_model->delete();
            $user_profile_model->file_id = null;
            $user_profile_model->save();
        }
    }
    
    
    public function action_ajax_get_locality()
    {
        $geonames = new Geonames();
        
        if(isset($_GET['search']))
        {
            $places = $geonames->search(array('name_startsWith' => $_GET['search'],
                                              'featureClass'    => 'P',
                                              'style'           => 'full',
                                              'maxRows'         => 6,
                                              'lang'            => I18n::lang(),
                                             
                                              
                ));
            
            $response = array();
            $places_array = array();
            foreach($places as $place)
            {
                //$place_name = $place->name.' - '.$place->adminName1;
                $place_name = $place->name;
                if(!in_array($place_name, $places_array))
                    $response[] = array(null, $place_name, null,'<div style="padding: 10px">'.$place_name.'</div>');
                
                $places_array[] = $place_name;                                
            }
            
            $this->response->body( json_encode($response));
            
        }
        
    }
    
    public function action_privacy()
    {
       $content_view = View::factory('content');      
       $settings_template_view = View::factory('settings/template'); 
          
       $settings_template_view->set('content', $this->generate_privacy());
       $settings_template_view->set('menu_selected', 3);
       $content_view->set('content', $settings_template_view);
       $this->template->set('body', $content_view);   
    }
    
    public function action_ajax_privacy()
    {
        $content = array('content' => $this->generate_privacy()->render());
        $this->response->body(json_encode($content));     
    }
    
    public function action_ajax_save_privacy()
    {
        if ($_POST)
        {
            $user_model = Auth::instance()->get_user();
            $user_privacy = $user_model->user_privacy;
            
            try
            {
                 
                $user_privacy->values($_POST, array('view_profile_permission',
                                                    'send_invitation_permission',
                                                    'comment_project_permission',
                                                    'send_message_permission',
                                                    'new_message_notification',
                                                    'new_invitation_notification',                                                   
                                                    'new_comment_notification',
                                                    'new_project_notification'));
                 
                $user_privacy->save();
                $output = array('success' => 'true',
                                'message' => 'Privacy settings saved');
             }
             catch (ORM_Validation_Exception $e)
             {
                 $output = array('success' => 'false', 
                                 'message' => 'Oh no!', 
                                 'errors'  => $e->errors('validation'));
             }
                           
             $this->response->body(json_encode($output));

        }
    }
    
    private function generate_privacy()
    {
         $user_model = Auth::instance()->get_user();
         $user_privacy_model = $user_model->user_privacy;
        
         $settings_privacy_view = View::factory('settings/privacy');
         $settings_privacy_view->set('user_privacy',$user_privacy_model);
       
         return $settings_privacy_view;
    }
}